import json
import time
from os import listdir, system
from utils.restApi import postGps
from utils.config import logpath, gpsApi_url, result_path, backup_path
from os.path import join,getmtime
from tendo.singleton import SingleInstance
from utils.logger import Logger

gps_trans_logger = Logger(filename=f'{logpath}/gps_transfer.log').logger
gps_trans_logger.info("gps_transfer start!")

try:
    Single = SingleInstance()
except:
    gps_trans_logger.error('gps transfer process already  exist! ')
    exit()


def gpsTransferSever():
    gpsJpath = join(result_path, 'gps')

    gpsBackFile = join(backup_path, 'gps', time.strftime("%Y%m%d%H%M%S", time.localtime()) + '.txt')
    with open(gpsBackFile, 'w') as g:
        g.write("#ctime, deviceid, appkey, secret, gpsdata, speed, height_offset, isstart \n")

    while True:
        time.sleep(0.5)
        gpsfiles = listdir(gpsJpath)
        gpsfiles.sort()
        for file in gpsfiles:
            time.sleep(0.01)
            if file.split('.')[-1] != 'json':
                continue

            datafile = join(gpsJpath, file)
            if time.time() - getmtime(datafile) < 1:
                break
            with open(datafile) as f:
                content = f.read()

            if not content:
                break

            gData = json.loads(content)
            # gps_trans_logger.info(data)
            r = postGps(gpsApi_url, gData)
            if r is None:
                gps_trans_logger.error('postGPS return None, 请检查网络!')
                time.sleep(1)
                break
            elif r == 'Connection refused':
                gps_trans_logger.error('Connection refused, 请检查网络!')
                time.sleep(1)
                break
            else:
                # gps_trans_logger.info(f"{r}, {r.text}")
                returnData = json.loads(r.text)
                if returnData['msg'] == 'success':
                    gps_trans_logger.info(f"{gData}\n  gps 高程" + "   上传成功!  \n")

                    with open(gpsBackFile, 'a') as g:
                        g.write(f"{json.dumps(gData)}\n")
                    system(f"rm -rf {datafile}")
                    # system(f"mv {datafile} {join(backup_path, 'gps/')}")
                else:
                    gps_trans_logger.error(f"\n gps 高程数据上传失败!  back code:{returnData} \n")


if __name__ == '__main__':
    gpsTransferSever()
